package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.ItCompany;
import com.ruoyi.system.domain.ItTopic;
import com.ruoyi.system.service.IItCompanyService;
import com.ruoyi.system.service.IItTopicService;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 公司基本信息Controller
 *
 * @author ruoyi
 * @date 2022-01-26
 */
@RestController
@RequestMapping("/mini/company")
public class ItCompanyController extends BaseController {
    @Autowired
    private IItCompanyService itCompanyService;
    @Autowired
    private IItTopicService itTopicService;


    /**
     * 查询公司基本信息列表
     */
//    @PreAuthorize("@ss.hasPermi('mini:company:list')")
    @GetMapping("/list")
    public TableDataInfo list(ItCompany itCompany) {
        startPage();
        List<ItCompany> list = itCompanyService.selectItCompanyList(itCompany);
        return getDataTable(list);
    }


    /**
     * 导出公司基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:company:export')")
    @Log(title = "公司基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ItCompany itCompany) {
        List<ItCompany> list = itCompanyService.selectItCompanyList(itCompany);
        ExcelUtil<ItCompany> util = new ExcelUtil<ItCompany>(ItCompany.class);
        util.exportExcel(response, list, "公司基本信息数据");
    }

    /**
     * 获取公司基本信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:company:query')")
    @GetMapping(value = "/{itId}")
    public AjaxResult getInfo(@PathVariable("itId") String itId) {
        ItCompany itCompany = new ItCompany();
        itCompany.setItId(itId);
        List<ItCompany> list = itCompanyService.selectItCompanyList(itCompany);
//        return AjaxResult.success(itCompanyService.selectItCompanyByItId(itId));
//        list.get(0).setFilePath(RuoYiConfig.getFilePath());
        list.get(0).setFilePath("http://192.168.31.230:8080");
        return AjaxResult.success(list.get(0));
    }

    /**
     * 新增公司基本信息
     */
//    @PreAuthorize("@ss.hasPermi('system:company:add')")
//    @Log(title = "公司基本信息", businessType = BusinessType.INSERT)
    @PostMapping("/adds")
//    public AjaxResult add(@RequestBody ItCompany itCompany, @RequestParam("avatarfile") List<MultipartFile> file) throws IOException {
    public AjaxResult adds(@RequestBody ItCompany itCompany) throws IOException {
        itCompany.setCreateTime(new Date());//创建时间
//        if (StringUtils.isEmpty(itCompany.getItSubjectId())) {
//            itCompany.setItSubjectId(null);
//        }
        //话题可以创建话题也可以选择话题,也可以没有话题
        //是否没有话题
        if (itCompany.getItSubjectId() != null && !"".equals(itCompany.getItSubjectId())) {
            //有话题判断是新增的话题还是选择的话题,选择的话题为数字,新增的话题为字符串
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean matches = pattern.matcher(itCompany.getItSubjectId()).matches();
            //不等于数字的情况下,需要新增话题,返回来话题的id进行存入
            //是数字则判断是话题id还是新增的话题就是数字
            if (matches) {
                List<Map<Object, Object>> maps = itTopicService.selectItTopicListCount();
                int a = 0;
                for (Map m : maps) {
                    String it_id = m.get("it_id") + "";
                    //如果传过来的数字跟数据库话题表的id一致则就是关联话题表
                    if (it_id.equals(itCompany.getItSubjectId())) {
                        break;
                    } else {
                        a++;
                        if (a == maps.size()) {
                            matches = false;
                        }
                    }
                }
            }
            if (matches == false) {
                ItTopic itTopic = new ItTopic();
                itTopic.setCreateTime(new Date()); //添加话题时间
                itTopic.setItTopic(itCompany.getItSubjectId());//话题内容
                itTopic.setIsDeleted("0"); //是否删除0否1是
                itTopicService.insertItTopic(itTopic);
                //获取到新增话题返回的id,并存入发帖表
                itCompany.setItSubjectId(itTopic.getItId() + "");
            }
        }
        return toAjax(itCompanyService.insertItCompany(itCompany));
    }

    /**
     * 图片上传
     */
    @Log(title = "图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            return AjaxResult.success("img", avatar);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
    /**
     * 图片上传
     */
    @Log(title = "图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/avatarFile")
    public AjaxResult avatarFile(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            Map<String,String> map = new HashMap<>();
            map.put("filePath",avatar);
//            map.put("realPath",RuoYiConfig.getFilePath() + avatar);
            map.put("realPath","http://192.168.31.230:8080" + avatar);
            return AjaxResult.success("img", map);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 修改公司基本信息
     */
    @PreAuthorize("@ss.hasPermi('system:company:edit')")
    @Log(title = "公司基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ItCompany itCompany) {
        return toAjax(itCompanyService.updateItCompany(itCompany));
    }

    /**
     * 删除公司基本信息
     */
    @PreAuthorize("@ss.hasPermi('system:company:remove')")
    @Log(title = "公司基本信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{itIds}")
    public AjaxResult remove(@PathVariable String[] itIds) {
        return toAjax(itCompanyService.deleteItCompanyByItIds(itIds));
    }
}
